/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kurvykurvy.core.ui;

import com.kurvykurvy.image.ImageLoader;
import com.kurvykurvy.image.ImageSlide;
import com.kurvykurvy.image.LoadedImage;
import java.awt.FlowLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.util.Exceptions;

/**
 * Top component which displays something.
 */
@ConvertAsProperties( dtd = "-//com.kurvykurvy.core.ui//ImageStrip//EN", autostore = false )
public final class ImageStripTopComponent 
        extends TopComponent
        implements PropertyChangeListener
{
    private static ImageStripTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "ImageStripTopComponent";

    Vector<LoadedImage> loadedImages;
    Vector<ImageSlide> slides;

    boolean refreshRequired = false;

    public ImageStripTopComponent()
    {
        initComponents();
        setName( NbBundle.getMessage( ImageStripTopComponent.class, "CTL_ImageStripTopComponent" ) );
        setToolTipText( NbBundle.getMessage( ImageStripTopComponent.class, "HINT_ImageStripTopComponent" ) );
//        setIcon(ImageUtilities.loadImage(ICON_PATH, true));
        putClientProperty( TopComponent.PROP_CLOSING_DISABLED, Boolean.FALSE );
        putClientProperty( TopComponent.PROP_DRAGGING_DISABLED, Boolean.FALSE );
        putClientProperty( TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE );
        putClientProperty( TopComponent.PROP_SLIDING_DISABLED, Boolean.FALSE );
        putClientProperty( TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE );
        putClientProperty( TopComponent.PROP_KEEP_PREFERRED_SIZE_WHEN_SLIDED_IN, Boolean.FALSE );

        ImageLoader.getInstance().addPropertyChangeListener( this );
    }

    public void refreshStrip()
    {
        ImageLoader loader = ImageLoader.getInstance();
        loadedImages = loader.getImages();

        imageStrip.removeAll();
        ( (FlowLayout) imageStrip.getLayout() ).setAlignment( FlowLayout.LEFT );
        for( Iterator<LoadedImage> it = loadedImages.iterator(); it.hasNext(); )
        {
            LoadedImage img = it.next();
            ImageSlide slide = new ImageSlide( img );
            addSlide( slide );
        }
        refreshRequired = false;
    }

    public void addLoadedImage( LoadedImage img )
    {
        if( loadedImages == null )
            loadedImages = new Vector<LoadedImage>();

        if( !loadedImages.contains( img ) )
        {
            loadedImages.add(  img );
            addSlide( new ImageSlide( img ) );
        }
    }

    public void removeLoadedImage( LoadedImage img )
    {
        if( loadedImages != null )
        {
            loadedImages.remove( img );
            refreshStrip();
        }
    }

    public void addSlide( final ImageSlide slide )
    {
        SwingUtilities.invokeLater(
            new Runnable()
            {
                public void run()
                {
                    imageStrip.add( slide );
                    repaint( imageStrip.getVisibleRect() );
                }
            }
        );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        imageStripView = new javax.swing.JScrollPane();
        imageStrip = new javax.swing.JPanel();

        setMaximumSize(new java.awt.Dimension(32767, 150));
        setMinimumSize(new java.awt.Dimension(0, 120));
        setPreferredSize(new java.awt.Dimension(1447, 120));

        imageStrip.setBackground(new java.awt.Color(255, 255, 255));
        imageStripView.setViewportView(imageStrip);
        imageStrip.setTransferHandler( new com.kurvykurvy.image.LoadedImageExportTransferHandler() );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imageStripView, javax.swing.GroupLayout.DEFAULT_SIZE, 1447, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imageStripView, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel imageStrip;
    private javax.swing.JScrollPane imageStripView;
    // End of variables declaration//GEN-END:variables

    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized ImageStripTopComponent getDefault()
    {
        if ( instance == null )
        {
            instance = new ImageStripTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the ImageStripTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ImageStripTopComponent findInstance()
    {
        TopComponent win = WindowManager.getDefault().findTopComponent( PREFERRED_ID );
        if ( win == null )
        {
            Logger.getLogger( ImageStripTopComponent.class.getName() ).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system." );
            return getDefault();
        }
        if ( win instanceof ImageStripTopComponent )
        {
            return (ImageStripTopComponent) win;
        }
        Logger.getLogger( ImageStripTopComponent.class.getName() ).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior." );
        return getDefault();
    }

    @Override
    public int getPersistenceType()
    {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened()
    {
        if( refreshRequired )
        {
            refreshStrip();
        }
    }

    @Override
    public void componentClosed()
    {
        refreshRequired = true;
    }

    void writeProperties( java.util.Properties p )
    {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty( "version", "1.0" );
        // TODO store your settings
    }

    Object readProperties( java.util.Properties p )
    {
        ImageStripTopComponent singleton = ImageStripTopComponent.getDefault();
        singleton.readPropertiesImpl( p );
        return singleton;
    }

    private void readPropertiesImpl( java.util.Properties p )
    {
        String version = p.getProperty( "version" );
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID()
    {
        return PREFERRED_ID;
    }

    public void propertyChange( final PropertyChangeEvent evt )
    {
        if( evt.getSource() == ImageLoader.getInstance() )
        {
            SwingUtilities.invokeLater(
                new Runnable()
                {
                        public void run()
                        {
                            try
                            {
                                if( evt.getNewValue() instanceof LoadedImage )
                                {
                                    LoadedImage image = (LoadedImage) evt.getNewValue();
                                    addLoadedImage( image );
                                }
                                Thread.sleep( 100 );
                                Thread.yield();
                            }
                            catch( InterruptedException irEx )
                            {
                                Exceptions.printStackTrace( irEx );
                                Thread.yield();
                            }
                        }
                }
            );
        }
    }
}
